package com.topideal.supplychain.hades.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.base.Throwables;
import com.topideal.supplychain.framework.exception.BusinessException;
import com.topideal.supplychain.hades.dto.ProjectViewDto;
import com.topideal.supplychain.hades.service.PersonalTimeCountService;
import com.topideal.supplychain.hades.service.ProjectTimeCountService;
import com.topideal.supplychain.hades.viewfilter.BasicInfoFilter;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;

/**
 * 基础数据
 *
 * @author xuxiaoyan
 * @date 2018-09-06 11:05
 */
@Controller
@RequestMapping("/basicInfo")
public class BasicInfoController {

    private static Logger logger = Logger.getLogger(BasicInfoController.class);

    @Autowired
    private ProjectTimeCountService projectTimeCountService;

    @Autowired
    private PersonalTimeCountService personalTimeCountService;

    /**
     * 项目工时统计 条件查询
     *
     * @return
     */
    @RequestMapping(value = {"/project"})
    public ModelAndView projectList(@ModelAttribute("filter") BasicInfoFilter filter,
                                    @RequestParam(defaultValue = "1", required = false) int page,
                                    @RequestParam(defaultValue = "10", required = false) int rows) {

        ModelAndView view = new ModelAndView("basicInfo/projectList");
        PageInfo<ProjectViewDto> pageInfo = null;
        try {
            pageInfo = PageHelper.startPage(page, rows)
                    .doSelectPageInfo(() -> projectTimeCountService.selectProjectTimeSummary(filter));
        } catch (Exception e) {
            logger.error("查找项目工时统计出错！", e);
            view.addObject("errorMsg", "查找项目工时统计出错！");
        }


        view.addObject("pageInfo", pageInfo);
        view.addObject("page", page);
        view.addObject("rows", rows);
        view.addObject("filter", filter);
        return view;
    }

    /**
     * 项目任务详情
     *
     * @return
     */
    @RequestMapping(value = {"/projectDetail/{pId}"})
    public String projectDetail(@PathVariable String pId, ModelMap map,
                                @RequestParam(defaultValue = "1", required = false) int page,
                                @RequestParam(defaultValue = "10", required = false) int rows) {
        PageInfo<ProjectViewDto> pageInfo = null;
        BasicInfoFilter filter = new BasicInfoFilter();
        filter.setPId(pId);
        try {
            pageInfo = PageHelper.startPage(page, rows)
                    .doSelectPageInfo(() -> projectTimeCountService.selectProjectTimeDetail(filter));
            //int a = 1/0;
        } catch (Exception e) {
            logger.error("查找项目工时详情出错！", e);
            map.addAttribute("errorMsg", "查找项目工时详情出错！");
        }

        map.addAttribute("pageInfo", pageInfo);
        map.addAttribute("page", page);
        map.addAttribute("rows", rows);
        map.addAttribute("pId", pId);
        return "basicInfo/projectDetail";
    }

    /**
     * 模块任务详情
     *
     * @return
     */
    @RequestMapping(value = {"/componentDetail/{cId}"})
    public String componentDetail(@PathVariable String cId, ModelMap map,
                                  @RequestParam(defaultValue = "1", required = false) int page,
                                  @RequestParam(defaultValue = "10", required = false) int rows) {
        PageInfo<ProjectViewDto> pageInfo;
        BasicInfoFilter filter = new BasicInfoFilter();
        filter.setCId(cId);
        try {
            pageInfo = PageHelper.startPage(page, rows)
                    .doSelectPageInfo(() -> projectTimeCountService.selectComponentTimeDetail(filter));
        } catch (Exception e) {
            logger.error("查找模块工时详情出错！", e);
            throw new BusinessException("查找模块工时详情出错！");
        }

        map.addAttribute("pageInfo", pageInfo);
        map.addAttribute("page", page);
        map.addAttribute("rows", rows);
        map.addAttribute("cId", cId);
        return "basicInfo/componentDetail";
    }


    /**
     * 个人工时统计 条件查询
     *
     * @return
     */
    @RequestMapping(value = {"/personal"})
    public ModelAndView personalList(@ModelAttribute("filter") BasicInfoFilter filter,
                                     @RequestParam(defaultValue = "1", required = false) int page,
                                     @RequestParam(defaultValue = "10", required = false) int rows) {

        ModelAndView view = new ModelAndView("basicInfo/personalList");
        PageInfo<ProjectViewDto> pageInfo;
        try {
            pageInfo = PageHelper.startPage(page, rows)
                    .doSelectPageInfo(() -> personalTimeCountService.selectTimeSummary(filter));
        } catch (Exception e) {
            logger.error("查找个人工时统计出错！", e);
            throw new BusinessException("查找个人工时统计出错！");
        }

        view.addObject("pageInfo", pageInfo);
        view.addObject("page", page);
        view.addObject("rows", rows);
        view.addObject("filter", filter);
        return view;
    }

    /**
     * 人员工时详情
     *
     * @return
     */
    @RequestMapping(value = {"/personalDetail/{userKey}/{isSum}"})
    public String personalDetail(@PathVariable String userKey, @PathVariable String isSum, ModelMap map,
                                 @RequestParam(defaultValue = "1", required = false) int page,
                                 @RequestParam(defaultValue = "10", required = false) int rows) {
        PageInfo<ProjectViewDto> pageInfo;
        BasicInfoFilter filter = new BasicInfoFilter();
        filter.setUserKey(userKey);
        if (StringUtils.isEmpty(isSum)) {
            isSum = "true";
        }
        // 根据前台传来的是否合并标识，判断显示是否合并
        try {
            boolean isSumFlag = Boolean.parseBoolean(isSum);
            pageInfo = PageHelper.startPage(page, rows)
                    .doSelectPageInfo(() -> {
                        if (isSumFlag) {
                            personalTimeCountService.selectTimeDetail(filter);
                        } else {
                            personalTimeCountService.selectEveryTimeDetail(filter);
                        }
                    });
        } catch (Exception e) {
            logger.error("查找人员工时详情出错！", e);
            throw new BusinessException("查找人员工时详情出错！");
        }

        map.addAttribute("pageInfo", pageInfo);
        map.addAttribute("isSum", isSum);
        map.addAttribute("userKey", userKey);
        map.addAttribute("page", page);
        map.addAttribute("rows", rows);
        return "basicInfo/personalDetail";
    }

    /**
     * 导出项目模块工时统计列表
     */
    @RequestMapping("/projectListExport")
    public String projectListExport(BasicInfoFilter basicInfoFilter, HttpServletResponse response) {
        try {
            projectTimeCountService.exportProjectListExcel(basicInfoFilter, response);
            return "success";
        } catch (Exception e) {
            logger.error(Throwables.getStackTraceAsString(e));
            return e.getMessage();
        }
    }


    /**
     * 项目详情导出限制判断
     *
     * @param pId
     * @return
     */
    @RequestMapping(value = {"/projectDetailIsExport/{pId}"})
    @ResponseBody
    public String projectDetailIsExport(@PathVariable String pId) {
        BasicInfoFilter filter = new BasicInfoFilter();
        JSONObject data = new JSONObject();
        filter.setPId(pId);
        try {
            projectTimeCountService.isExportProjectDetailExcel(filter);
            data.put("errorMsg", "");
            return JSONObject.toJSONString(data);
        } catch (BusinessException e) {
            logger.error(e);
            data.put("errorMsg", e.getMessage());
            return JSONObject.toJSONString(data);
        } catch (Exception e) {
            logger.error(Throwables.getStackTraceAsString(e));
            data.put("errorMsg", e.getMessage());
            return JSONObject.toJSONString(data);
        }

    }

    /**
     * 导出项目详情
     *
     * @return
     */
    @RequestMapping(value = {"/projectDetailExport/{pId}"})
    public void projectDetailExport(@PathVariable String pId, HttpServletResponse response) {
        BasicInfoFilter filter = new BasicInfoFilter();
        ModelAndView view = new ModelAndView();
        filter.setPId(pId);
        try {
            projectTimeCountService.exportProjectDetailExcel(filter, response);
        } catch (Exception e) {
            logger.error(Throwables.getStackTraceAsString(e));
            view.setViewName("error/500");
            view.addObject("errorMsg", e.getMessage());
        }
    }

    /**
     * 导出模块详情
     *
     * @return
     */
    @RequestMapping(value = {"/componentDetailExport/{cId}"})
    public String componentDetailExport(@PathVariable String cId, HttpServletResponse response) {
        BasicInfoFilter filter = new BasicInfoFilter();
        filter.setCId(cId);
        try {
            projectTimeCountService.exportComponentDetailExcel(filter, response);
            return "success";
        } catch (Exception e) {
            logger.error(Throwables.getStackTraceAsString(e));
            return e.getMessage();
        }
    }

    /**
     * 导出人员工时统计列表
     */
    @RequestMapping("/personalExport")
    public String personalExport(BasicInfoFilter basicInfoFilter, HttpServletResponse response) {
        try {
            personalTimeCountService.exportPersonalListExcel(basicInfoFilter, response);
            return "success";
        } catch (Exception e) {
            logger.error(Throwables.getStackTraceAsString(e));
            return e.getMessage();
        }
    }

    /**
     * 导出人员工时详情
     *
     * @return
     */
    @RequestMapping(value = {"/personalDetailExport/{userKey}/{isSum}"})
    public String personalDetailExport(@PathVariable String userKey, @PathVariable String isSum, HttpServletResponse response) {
        BasicInfoFilter filter = new BasicInfoFilter();
        filter.setUserKey(userKey);
        if (StringUtils.isEmpty(isSum)) {
            isSum = "true";
        }
        try {
            boolean isSumFlag = Boolean.parseBoolean(isSum);
            if (isSumFlag) {
                personalTimeCountService.exportTimeDetailExcel(filter, response);
            } else {
                personalTimeCountService.exportEveryTimeDetailExcel(filter, response);
            }
            return "success";
        } catch (Exception e) {
            logger.error(Throwables.getStackTraceAsString(e));
            return e.getMessage();
        }
    }
}
